<template>
  <div class="draggable-upload-group">
    <draggable
      v-model="imageList"
      class="draggable-upload-group-show-section"
      chosen-class="chosen"
      force-fallback="true"
      :group="group"
      animation="1000"
      @start="handleImageOnStart"
      @end="handleImageOnEnd"
    >
      <transition-group class="draggable-upload-group-transition-section">
        <div
          v-for="(item, index) in imageList"
          :key="item.id"
          class="draggable-upload-group-show-list"
        >
          <img
            class="el-upload-list__item-thumbnail"
            :src="item.url"
            alt="item.name"
          >
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              title="放大查看"
              @click="handleImagePictureCardPreview(item, index)"
            >
              <i class="el-icon-zoom-in" />
            </span>
            <!-- <span
            class="el-upload-list__item-delete"
            @click="handleImageDownload(item)"
            >
            <i class="el-icon-download"></i>
            </span>-->
            <span
              class="el-upload-list__item-delete"
              title="删除图片"
              @click="handleImageRemove(item)"
            >
              <i class="el-icon-delete" />
            </span>
          </span>
        </div>
      </transition-group>
    </draggable>
    <el-upload
      ref="thumbnailUpload"
      class="draggable-upload-group-uploadbar"
      :action="action"
      list-type="picture-card"
      :limit="limit"
      :auto-upload="true"
      :on-exceed="handleImageExceed"
      :before-upload="handleImageBeforeUpload"
      :on-success="handleImageUploadSuccess"
      :on-error="handleImageUploadError"
      :file-list="imageList"
      :show-file-list="false"
      :accept="acceptType"
      :multiple="multiple"
    >
      <i slot="default" class="el-icon-plus" />
    </el-upload>
    <!-- 图片查看器 -->
    <jsp-image-viewer
      :show="imageViewerVisible"
      :url-list="imageViewerList"
      @close="imageViewerVisible=false"
    />
  </div>
</template>

<script>
import JspImageViewer from '@/components/JspImageViewer'
import draggable from 'vuedraggable'

export default {
  name: 'JspImageUpload',
  components: {
    JspImageViewer,
    draggable
  },
  props: {
    // 默认列表
    defaultList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 上传地址
    action: {
      type: String,
      default: ''
    },
    // 上传类型：不填写默认所有
    // 格式：.jpg,.png,.gif,.bmp等
    accept: {
      type: String,
      default: ''
    },
    // 上传数量限制
    limit: {
      type: Number,
      default: 1
    },
    // 上传数量限制，默认2M
    size: {
      type: Number,
      default: 2
    },
    // 批量上传支持
    multiple: {
      type: Boolean,
      default: false
    },
    // 分组（组之间可进行拖拽）
    group: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageViewerVisible: false,
      imageViewerList: [],
      imageList: this.defaultList,
      acceptType: this.accept ? this.accept : 'image/*'
    }
  },
  methods: {
    // 移除图片
    handleImageRemove(file) {
      this.imageList = this.imageList.filter((currentValue) => {
        return currentValue.uid !== file.uid
      })
      this.change()
      this.$emit('remove', file, this.imageList)
    },
    // 预览图片
    handleImagePictureCardPreview(file, index) {
      this.imageViewerVisible = true
      const imageViewFilter = this.imageList.map(
        (currentValue) => currentValue.url
      )
      const beforeList = imageViewFilter.splice(index)
      this.imageViewerList = beforeList.concat(imageViewFilter)
    },
    // 关闭图片查看器
    handleCloseimageViewerVisible() {
      this.imageViewerVisible = false
    },
    // 下载图片
    handleImageDownload(file) {
      // console.log(file)
    },
    // 上传数量限制提示
    handleImageExceed(files, fileList) {
      this.$message.warning(`最多支持上传 ${this.limit} 张图片！`)
    },
    // 上传大小检验
    handleImageBeforeUpload(file) {
      let isFileType = true
      const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (this.accept !== '') {
        isFileType = this.acceptType.split(',').some((e) => {
          return e.replace(/\s+/g, '').toLowerCase() === ext
        })
        if (!isFileType) {
          this.$message.error(
            '文件类型不正确，支持类型' + this.acceptType + '，请重新选择!'
          )
        }
      }
      const isSize = file.size / 1024 / 1024 < this.size
      if (!isSize) {
        this.$message.error('图片大小不能超过 ' + this.size + 'MB!')
      }
      return isFileType && isSize
    },
    // 上传成功
    handleImageUploadSuccess(response, file, fileList) {
      // response数据结构由后端生成
      if (response.status === 'success') {
        // 以下内容在实际项目开发中还需按需进行修改
        const { id, name, path, url } = response
        this.imageList.push({ id: id, name: name, path: path, url: url })
        this.change()
      }
      this.$emit('success', response, file, fileList)
    },
    // 上传失败：上传请求地址、参数错误或服务器请求错误等情况
    handleImageUploadError(err, file, fileList) {
      this.$emit('error', err, file, fileList)
    },
    // 拖拽开始
    handleImageOnStart(e) {
      this.$emit('dragStart', e, this.imageList)
    },
    // 拖拽结束
    handleImageOnEnd(e) {
      this.change()
      this.$emit('dragEnd', e, this.imageList)
    },
    // 改变：上传成功、删除图片、拖拽结束时激活
    // 返回：当前排过序的图片id集、图片数组
    change() {
      const ids = this.imageList
        .map((currentValue) => currentValue.id)
        .join(',')
      const result = {
        ids,
        imageList: this.imageList
      }
      this.$emit('change', result)
    }
  }
}
</script>

<style>
</style>
